//
//  KSRadioView.swift
//  PigManager
//
//  Created by 邱仙凯 on 2020/8/7.
//  Copyright © 2020 Much. All rights reserved.
//

import UIKit

class KSRadioView: UIView {
    
    var btnClosure:((Int)->())?
    private var selectedBtn:KSRadioButton?
    private var bHeight:CGFloat = 30
    var selectedFen:String?
    
    var ksBtnArr = [KSRadioButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        for i in 0...10 {
            let btn = KSRadioButton()
            btn.tag = i
            btn.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
            addSubview(btn)
            ksBtnArr.append(btn)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var itemArr:[String]? {
        didSet {
            if let itemArr = itemArr {
                
                for item in ksBtnArr {
                    item.isHidden = true
                    item.isSelected = false
                }
               
                for i in 0..<itemArr.count {
                    let btn = ksBtnArr[i]
                    btn.isHidden = false
                     btn.frame = CGRect(x:0,y: bHeight * CGFloat(i) ,width: self.ks_width,height: bHeight)
                    btn.setTitle(itemArr[i].sufChar(char: ":"), for: .normal)
                    if let selectedFen = selectedFen,selectedFen == itemArr[i].preChar(char: ":") {
                        btn.isSelected = true
                        selectedBtn = btn
                    }
                }
            }
        }
    }
    
    @objc func btnAction(sender:KSRadioButton) {
        selectedBtn?.isSelected = false
        selectedBtn = sender
        selectedBtn?.isSelected = true
        if let clo = self.btnClosure {
            clo(sender.tag)
        }
    }
}
class KSRadioButton: UIButton {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.titleLabel?.textAlignment = .left
        self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        self.setTitleColor(.darkGray, for: .normal)
        self.setImage(UIImage(named:"selectButton"), for: .normal)
        self.setImage(UIImage(named:"selectedButton"), for: .selected)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 设置imageView
        imageView?.frame = CGRect(x: 0 , y: 2, width: 26, height: 26)
        // 设置title
        titleLabel?.frame = CGRect(x: 30 , y: 0, width: self.frame.width - 30, height: 30)
        
    }
    
}
